#!/usr/bin/python

import sys
import os
import os.path
import codecs
import jrdUtils
from pyXls import *

#----------------------------------------------------
# Global Variables
#----------------------------------------------------

_l10nPath = 'gaia/jrd-l10n/'
_xlsPath = 'ffos_wimdata_ng/wlanguage/src/'

if (len(sys.argv) > 1):
    _xlsFile = sys.argv[1]
else:
    _xlsFile = "strings.xls"

_langList = jrdUtils.getLangsListFromJson()

# create workbook
_wb = Workbook()
_ws0 = _wb.add_sheet(u'MESSAGE')
_ws1 = _wb.add_sheet('Zone')
_ws2 = _wb.add_sheet('Deleted')

# Language starting position of excel file
_langStartPosition = 7

#----------------------------------------------------
# Functions
#----------------------------------------------------

def setStyles():
    fnt = Font()
    fnt.name = 'Times New Roman'
    al = Alignment()
    al.horz = Alignment.HORZ_LEFT
    al.vert = Alignment.VERT_CENTER
    style = XFStyle()
    style.font = fnt
    style.alignment = al
    return style

def writeAttrTitlesToSheet(style):
    _ws0.write(0, 0, u'RefName',style)
    _ws0.write(0, 1, u'ModOP',style)
    _ws0.write(0, 2, u'Info',style)
    _ws0.write(0, 3, u'ZoneType',style)
    _ws0.write(0, 4, u'IsMono',style)
    _ws0.write(0, 5, u'IsUK',style)
    _ws0.write(0, 6, u'IsGSM',style)
    _ws0.write(0, 7, u'IsTradUpdatable',style)

    _ws1.write(0, 0, u'zonetype', style)
    _ws1.write(0, 1, u'width', style)
    _ws1.write(0, 2, u'height', style)
    _ws1.write(0, 3, u'text_size', style)
    _ws1.write(0, 4, u'FontFamily', style)
    _ws1.write(0, 5, u'Italic', style)
    _ws1.write(0, 6, u'Bold', style)
    _ws1.write(0, 7, u'ZoneDesc', style)

    _ws2.write(0, 0, u'Name', style)
    _ws2.write(0, 1, u'LogDate', style)
    _ws2.write(0, 2, u'RefName', style)
    _ws2.write(0, 3, u'LogAction', style)

def writeMsgToSheet1(msgDict,style):
    #sort MSGDICT
    sortDict = sorted(msgDict.items(), key=lambda e:e[0], reverse=False)

    for item in sortDict:
        t_row = sortDict.index(item)+1
        #print item[0]
        #write ID to excel
        _ws0.write( t_row , 0, item[0], style)
        for lang in _langList:
            t_column = _langList.index(lang) + _langStartPosition
            if item[1].get(lang[0]):
                #write Translation to excel
                _ws0.write(t_row,t_column,(item[1])[lang[0]], style)

    #print sortDict

    #save files
    _wb.save(_xlsPath + _xlsFile)
    print 'Generate xls table successed! --> %s' % (_xlsPath + _xlsFile)

def readlinesFromL10nPath(style):
    print 'Start to read properties files...'
    msgs = []
    msgDict = {}

    for lang in _langList:
        #Write Title line of the EXCEL file
        t_row = 0
        t_column = _langList.index(lang) + _langStartPosition

        _ws0.write( t_row, t_column, lang[1], style)

        #write id and translation of each language
        for parent, dirnames, filenames in os.walk( _l10nPath + lang[0]):

            for filename in filenames:
                filepath = os.path.join(parent, filename)
                #filename without postfix
                fname = filename[:filename.find('.')]
                print "    filename:" + fname
                #parse id and strings of each .properties file
                if parent.find('communications') == -1 :
                    refNamePrefix = parent[parent.rfind('/')+1:] + ':' + fname
                else:
                    refNamePrefix = parent[parent.find('communications'):]
                    refNamePrefix = refNamePrefix.replace('/',':') + ':' +fname
                print "        parent name:" + refNamePrefix

                # file operation
                propertiesFile = codecs.open(filepath,'rb',"utf_8")
                #messages = propertiesFile.readlines()

                msgs = []
                # filter: remove COMMENTS and LINE BREAKS
                for line in propertiesFile:
                    if line[0] == '#' or line == '\n':
                        #print msg + 'Deleted!'
                        pass
                    else:
                        msgs.append(line)
                propertiesFile.close()

                # handle the messages after filter COMMENTS and LINE BREAKS
                #print msgs

                for msg in msgs:
                    str = msg.split('=')
                    #print(str)
                    s0 = str[0].strip()
                    s1 = str[1].strip()
                    id = refNamePrefix + ':' + s0
                    #print '\n',id, i, len(msgs)
                    if msgDict.get(id):
                        pass
                    else:
                        msgDict[id] = {}
                    langDict = msgDict[id]
                    langDict[lang[0]] = s1
    return msgDict

#----------------------------------------------------
# main
#----------------------------------------------------

def main():
    # set styles
    s = setStyles()
    # write head line to xls
    writeAttrTitlesToSheet(s)
    # generate a msgDict from l10n files
    msgDict = readlinesFromL10nPath(s)
    # write messsges to excel
    writeMsgToSheet1(msgDict,s)

if __name__ == '__main__':
    main()
